import archiver from 'archiver';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 获取项目根目录
const rootDir = path.resolve(__dirname, '..');
const output = fs.createWriteStream(path.join(rootDir, 'project.zip'));
const archive = archiver('zip', {
    zlib: { level: 9 } // 设置压缩级别
});

// 监听错误事件
archive.on('error', (err) => {
    throw err;
});

// 监听关闭事件
output.on('close', () => {
    console.log(`打包完成！总大小: ${(archive.pointer() / 1024 / 1024).toFixed(2)} MB`);
});

// 设置输出流
archive.pipe(output);

// 要排除的文件和目录
const excludes = [
    'node_modules',
    'dist',
    '.git',
    'project.zip',
    '.DS_Store'
];

// 递归添加文件
function addDirectoryToArchive(dirPath, relativePath = '') {
    const files = fs.readdirSync(dirPath);
    
    for (const file of files) {
        const fullPath = path.join(dirPath, file);
        const relPath = path.join(relativePath, file);
        
        // 检查是否在排除列表中
        if (excludes.includes(file)) {
            continue;
        }
        
        // 检查是否为目录
        if (fs.statSync(fullPath).isDirectory()) {
            addDirectoryToArchive(fullPath, relPath);
        } else {
            archive.file(fullPath, { name: relPath });
        }
    }
}

// 开始打包
console.log('开始打包项目...');
addDirectoryToArchive(rootDir);

// 完成打包
archive.finalize();